package com.lancoo.znbkxx.teacher.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.view.View
import android.webkit.WebView
import androidx.lifecycle.Observer
import com.lancoo.cpbase.authentication.base.AddressOperater
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.cpbase.authentication.base.HandleCallback
import com.lancoo.cpbase.authentication.base.LoginOperate
import com.lancoo.znbkxx.teacher.Ext.Companion.BASE_ADDRESS
import com.lancoo.znbkxx.teacher.Ext.Companion.INFOLIST
import com.lancoo.znbkxx.teacher.Ext.Companion.KEY
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.base.SharedPreferencesHelper
import com.lancoo.znbkxx.teacher.databinding.ActivitySplashBinding
import com.lancoo.znbkxx.teacher.ui.Presenter
import com.lancoo.znbkxx.teacher.ui.dialog.CommonDialog
import com.lancoo.znbkxx.teacher.ui.dialog.PrivacyDialog
import com.lancoo.znbkxx.teacher.utils.InitDataListener
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.MkUtils
import com.lancoo.znbkxx.teacher.utils.SPUtils
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import com.tencent.mmkv.MMKV

/**
 * @author : Admin
 * @date   : 2019/7/29 11:27
 * @desc   :
 */
class SplashActivity : BaseVMActivity<UserInfoViewModel, ActivitySplashBinding>() {
    private lateinit var mOperate: LoginOperate
    private lateinit var privacyDialog: PrivacyDialog
    private var mHandler: Handler? = null

    override fun providerVMClass(): Class<UserInfoViewModel>? {
        return UserInfoViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.activity_splash
    }

    override fun initView() {
        mOperate = LoginOperate(this)
        privacyDialog = PrivacyDialog(this, this)
        mHandler = Handler()
        showPrivacyDialog()
        val webView = WebView(this)
        webView.loadUrl("<br>" + "测试验证，不能删,已隐藏")
    }

    private fun goLogin() {
//        Handler().postDelayed(runnable, (5 * 100).toLong())
        mHandler!!.postDelayed({
            if (application.getSharedPreferences("firstEnter", Context.MODE_PRIVATE)
                            .getBoolean("isFirst", true)) {
                startActivity(Intent().setClass(this, GuideActivity::class.java))
                finish()
            } else {
//                goToLoginWidthIdentityJudgment(operate)
                this.goToLogin()
            }
        }, 0)
    }

    private fun goToLogin() {
        val result = mOperate.currentUserState
        if (result == 1) {
            if (CurrentUser.UserType == 1) {
                setLoginSuccessData(null,object :InitDataListener{
                    override fun fail() {
                        logOut()
                    }
                })
            } else {
                showCommonDialog()
            }
        } else {
            mOperate.goToLoginActivity(this, { listener ->
                //登录成功了，判断用户类型
                if (CurrentUser.UserType == 1) {
                    setLoginSuccessData(listener, null)
                } else {
                    listener.handleUserTypeFail(1)
                }
            }, { finish() }, false)
        }
    }

    private fun setLoginSuccessData(listener: HandleCallback?, initDataListener: InitDataListener?) {
        val mAddress = AddressOperater(this)
        BASE_ADDRESS = mAddress.baseAddress
        MMKV.defaultMMKV()?.encode("BASE_ADDRESS", BASE_ADDRESS)
        KEY = LancooUtils.getBase64StuID(CurrentUser.UserID)
        MkUtils.encode("KEY", KEY)
        viewModel.getSystemConfigInfo(listener,initDataListener, CurrentUser.Token, "C", CurrentUser.UserID)
    }

    override fun startObserve() {
        viewModel.baseInfo.observe(this, Observer {
            if (it.isNullOrEmpty()) gotoOneonOneActivity() else gotoMainActivity()
        })
        viewModel.mErrorMsg.observe(this, Observer {
            if (null == INFOLIST) gotoOneonOneActivity() else gotoMainActivity()
        })
    }

    //当前用户身份非教师时不能登录
    private fun showCommonDialog() {
        CommonDialog(this, this).apply {
            message.set("登录失败，请使用教师账号登录")
        }.setConfirmListener {
            logOut()
        }.show()
    }

    private fun logOut() {
        mOperate.logOutOnlyClearMemory()
        mOperate.goToLoginActivity(this, { listener ->
            //登录成功了，判断用户类型
            if (CurrentUser.UserType == 1) {
                setLoginSuccessData(listener, null)
            } else {
                listener.handleUserTypeFail(1)
            }
        }, { finish() }, false)
    }

    private fun showPrivacyDialog() {
        SharedPreferencesHelper.init(this, "LancooListenClass")
        val isAgreePermissions = SharedPreferencesHelper.getBoolean("isAgreePermissions", false)
        var count = SPUtils.get("isFirstEnterApp", 0)
        if (count == 0 && !isAgreePermissions) {
            privacyDialog.setPresenter(object : Presenter {
                override fun onClick(view: View?) {
                    SharedPreferencesHelper.applyBoolean("isAgreePermissions", true)
                    SPUtils.put("isFirstEnterApp", ++count)
                    //点击同意，正常登陆流程
                    privacyDialog.dismiss()
                    goLogin()
                }

                override fun onCancel(view: View?) {
                    SharedPreferencesHelper.applyBoolean("isAgreePermissions", false)
                    //  点击不同意，直接退出app
                    SPUtils.put("isFirstEnterApp", 0)
                    privacyDialog.dismiss()
                    //                    finish()
                    goLogin()
                }
            }).show()
        } else {
            SPUtils.put("isFirstEnterApp", ++count)
            goLogin()
        }
    }

    private fun gotoMainActivity() {
        startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        finish()
    }

    private fun gotoOneonOneActivity() {
        startActivity(Intent(this@SplashActivity, OneonOneActivity::class.java))
        finish()
    }
}